/**
 * 
 */
package xiaojian.toolkit.netty.handler.codec.http.response;

import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.*;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationTargetException;

/**
 * @author hp
 *
 */
public class NettyHttpResponseBuilder implements HttpResponseBuilder {

	private static final Logger logger = LoggerFactory
			.getLogger(NettyHttpResponseBuilder.class);

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.skymobi.http.HttpResponseBuilder#build(org.apache.asyncweb.common
	 * .HttpRequest, java.lang.Object)
	 */
	public HttpResponse build(Object source) {
		FullHttpResponse resp = new DefaultFullHttpResponse(
				HttpVersion.HTTP_1_1, HttpResponseStatus.OK);

		try {
			resp.setStatus((HttpResponseStatus) PropertyUtils.getProperty(
					source, "status"));

			String contentType = BeanUtils.getProperty(source, "contentType");
			if (null != contentType) {
				resp.headers().set(HttpHeaders.Names.CONTENT_TYPE, contentType);
			}

			byte[] bytes = (byte[]) PropertyUtils
					.getProperty(source, "content");
			if (null != bytes) {
				resp.content().writeBytes(bytes);
			}

			String contentLength = BeanUtils.getProperty(source,
					"contentLength");
			if (null != contentLength && !contentLength.equals("0")) {
				resp.headers().set(HttpHeaders.Names.CONTENT_LENGTH,
						contentLength);
			} else {
				resp.headers().set(HttpHeaders.Names.CONTENT_LENGTH,
						bytes == null ? 0 : bytes.length);
			}

			String contentRange = BeanUtils.getProperty(source, "contentRange");
			if (null != contentRange) {
				resp.headers().set("Content-Range", contentRange);
			}
			String date = BeanUtils.getProperty(source, "date");
			if (null != date) {
				resp.headers().set("Date", date);
			}

			return resp;
		} catch (IllegalAccessException e) {
			logger.error("build:", e);
		} catch (InvocationTargetException e) {
			logger.error("build:", e);
		} catch (NoSuchMethodException e) {
			logger.error("build:", e);
		}
		return resp;
	}

}
